/**
 * 初始化
 */
(function () {
    /**
     * UI函数
     * @param options 配置参数
     * @constructor
     */
    function UI(options) {
        /**
         * 启动
         */
        this.setup = function () {
            let options = {
                width: options.width,
                height: options.height
            };
            // 创建一个 Pixi应用
            this.app = new PIXI.Application(options);
            this.stage = this.app.stage;
            document.body.appendChild(this.app.view);

            // 创建格子
            for (let i = 0; i < this.gridX; i++) {
                let rows = [];
                for (let j = 0; j < this.gridY; j++) {
                    let grid = new PIXI.Sprite(this.getGridUI(1));
                    grid.x = j * 50;
                    grid.y = i * 50;

                    // 格子的坐标
                    grid._mineX = i;
                    grid._mineY = j;
                    // 是否被标记，小旗子
                    grid._mineMark = false;
                    // 周围雷个数
                    grid._mineRoundCount = 0;
                    // 是否是雷，true是，false不是
                    grid._mineFlag = false;
                    // 是否已经点击过
                    grid._mineShow = false;

                    grid.width = 50;
                    grid.height = 50;

                    // 点击有效
                    grid.interactive = true;
                    // 鼠标移动上去变成小手
                    grid.buttonMode = true;
                    // 左键
                    grid.on('click', this.onClick);
                    // 右键
                    grid.on('rightclick', this.onRightClick);

                    //Add the rocket to the stage
                    this.stage.addChild(grid);

                    rows[j] = grid;
                }
                this.gridMapCache[i] = rows;
            }
        };

        /**
         * 获取格子UI
         * @param type
         */
        this.getGridUI = function (type) {
            let texture = this.gridUICache[type];
            if (null == texture) {
                texture = new PIXI.Texture(this.minTextureCache);
                // 灰色背景
                if (1 === type) {
                    texture.frame = new PIXI.Rectangle(1, 175, 86, 86)
                }
                // 旗子
                else if (2 === type) {
                    texture.frame = new PIXI.Rectangle(1, 1, 86, 86)
                }
                // 雷
                else if (3 === type) {
                    texture.frame = new PIXI.Rectangle(88, 88, 86, 86)
                }
                // 白块
                else if (4 === type) {
                    texture.frame = new PIXI.Rectangle(88, 175, 86, 86)
                }
                this.gridUICache[type] = texture;
            }
            return texture;
        };
        // 地雷图片缓存
        this.gridUICache = {};
        /**
         * 地雷图片
         */
        this.minTextureCache = PIXI.utils.TextureCache['mine1.jpg'];

        // 格子缓存
        this.gridMapCache = [];

        /**
         * application对象
         * @type {null}
         */
        this.app = null;
        /**
         * stage对象
         * @type {null}
         */
        this.stage = null;

        /**
         * 格子x轴个数
         * @type {number}
         */
        this.gridX = options.gridX;
        /**
         * 格子y轴个数
         * @type {number}
         */
        this.gridY = options.gridY;
        // 是否初始化过
        this.isInit = false;
        this.onClick = function () {

        };
        this.onRightClick = function () {

        };

        /**
         * 控制
         * @type {Control}
         */
        this.control = new Control(options.control);

        /**
         * 地雷对象
         * @type {Mine}
         */
        this.mine = new Mine(options.mine);
    }

    /**
     * 控制函数
     * @param options
     * @constructor
     */
    function Control(options) {
        /**
         * 游戏是否结束
         * @type {boolean}
         */
        this.gameOver = false;

        /**
         * 右键标记的雷的个数
         * @type {number}
         */
        this.markMineSzie = 0;
    }

    /**
     * 地雷函数
     * @param options 配置参数
     * @constructor
     */
    function Mine(options) {
        /**
         * 地雷个数
         * @type {number}
         */
        this.size = options.size;

        /**
         * 初始化地雷
         * @param cx click x
         * @param cy click y
         * @param gx grid x length
         * @param gy grid y length
         */
        this.initMine = function(cx, cy, gx, gy) {
            // 随机生成雷的位置
            function randomMine(filter) {
                let whileEnd = true
                do {
                    let _x = ~~(Math.random() * gx)
                    let _y = ~~(Math.random() * gy)

                    if (filter(_x, _y)) {
                        let _key = toKey(_x, _y)
                        if (!mm[_key]) {
                            mm[_key] = {
                                x: _x,
                                y: _y
                            }
                            mmLength++
                            if (mmLength === mineSize) {
                                whileEnd = false
                            }
                        }
                    }
                } while (whileEnd)
            }
        };

        this.countRoundMineSize = function () {

        }
    }

    // 加载资源
    PIXI.Loader.shared.add(['mine1.jpg']).load(new UI().setup);
})();


function setup() {
    let options = {
        width: 800,
        height: 550
    }
    // 创建一个 Pixi应用
    const app = new PIXI.Application(options)
    document.body.appendChild(app.view)

    // 获取舞台
    let stage = app.stage

    const gx = 10,
        gy = 15,
        // 10%的雷
        mineSize = 15
    let markMineSize = 0,
        // 是否已经结束
        isGameOver = false

    // 组合图片
    function loadMine() {
        // 灰色背景
        let base = PIXI.utils.TextureCache['mine1.jpg']
        let texture = new PIXI.Texture(base)
        texture.frame = new PIXI.Rectangle(1, 175, 86, 86)
        // 旗子
        let texture2 = new PIXI.Texture(base)
        texture2.frame = new PIXI.Rectangle(1, 1, 86, 86)
        // 雷
        let texture3 = new PIXI.Texture(base)
        texture3.frame = new PIXI.Rectangle(88, 88, 86, 86)
        // 白块
        let texture4 = new PIXI.Texture(base)
        texture4.frame = new PIXI.Rectangle(88, 175, 86, 86)

        // 格子
        let gridMap = []

        for (let i = 0; i < gx; i++) {
            var rows = []
            for (let j = 0; j < gy; j++) {
                let rocket = new PIXI.Sprite(texture)
                //Position the rocket sprite on the canvas
                rocket.x = j * 50
                rocket.y = i * 50

                // 格子的坐标
                rocket._mineX = i
                rocket._mineY = j
                // 是否被标记，小旗子
                rocket._mineMark = false
                // 周围雷个数
                rocket._mineRoundCount = 0
                // 是否是雷，true是，false不是
                rocket._mineFlag = false
                // 是否已经点击过
                rocket._mineShow = false

                rocket.width = 50
                rocket.height = 50

                // 点击有效
                rocket.interactive = true
                // 鼠标移动上去变成小手
                rocket.buttonMode = true
                // 左键
                rocket.on('click', onClick)
                // 右键
                rocket.on('rightclick', rightClick)

                //Add the rocket to the stage
                stage.addChild(rocket)

                rows[j] = rocket
            }
            gridMap[i] = rows
        }

        console.log(gridMap)

        // 是否初始化过
        let initMineFlag = false
        // 地图
        let mineMap = [],
            mm = {},
            mmLength = 0

        // 初始化雷
        function initMine(fx, fy) {
            // 排除点击的那个格子

            // 随机生成雷的位置
            function randomMine(filter) {
                let whileEnd = true
                do {
                    let _x = ~~(Math.random() * gx)
                    let _y = ~~(Math.random() * gy)

                    if (filter(_x, _y)) {
                        let _key = toKey(_x, _y)
                        if (!mm[_key]) {
                            mm[_key] = {
                                x: _x,
                                y: _y
                            }
                            mmLength++
                            if (mmLength === mineSize) {
                                whileEnd = false
                            }
                        }
                    }
                } while (whileEnd)
            }

            randomMine(function (_x, _y) {
                if (fx === _x && fy === _y) {
                    return false
                }
                return true
            })
            console.log(mm)
            // 显示雷
            // for (let key in mm) {
            //   let data = mm[key]
            //   var r = gridMap[data.x][data.y]
            //   r.texture = texture3
            // }

            countRoundMineSize()

            // for (let i = 0; i < gx; i++) {
            //   for (let j = 0; j < gy; j++) {
            //     let g = gridMap[i][j]
            //     if (g._mineFlag) {
            //       g.texture = texture3
            //     } else {
            //       let c = g._mineRoundCount
            //       renderMineSize(i, j, c)
            //       g.texture = texture4
            //     }
            //   }
            // }
        }

        // 计算周围雷数量
        function countRoundMineSize() {
            for (let i = 0; i < gx; i++) {
                for (let j = 0; j < gy; j++) {
                    let c = getMineSize(i, j)
                    let g = gridMap[i][j]
                    if (-1 === c) {
                        // 是雷
                        g._mineFlag = true
                    } else {
                        // 不是雷
                        g._mineRoundCount = c
                        g._mineFlag = false
                    }
                }
            }
        }

        function getMineSize(x, y) {
            // 判断自己是否是雷
            let key = toKey(x, y)
            if (mm[key]) {
                return -1
            }
            let size = 0
            // 左上
            if (x - 1 >= 0 && y - 1 >= 0) {
                if (mm[toKey(x - 1, y - 1)]) {
                    size++
                }
            }
            // 上
            if (x - 1 >= 0) {
                if (mm[toKey(x - 1, y)]) {
                    size++
                }
            }
            // 右上
            if (x - 1 >= 0 && y + 1 < gy) {
                if (mm[toKey(x - 1, y + 1)]) {
                    size++
                }
            }
            // 左
            if (y - 1 >= 0) {
                if (mm[toKey(x, y - 1)]) {
                    size++
                }
            }
            // 右
            if (y + 1 < gy) {
                if (mm[toKey(x, y + 1)]) {
                    size++
                }
            }
            // 左下
            if (x + 1 < gx && y - 1 >= 0) {
                if (mm[toKey(x + 1, y - 1)]) {
                    size++
                }
            }
            // 下
            if (x + 1 < gx) {
                if (mm[toKey(x + 1, y)]) {
                    size++
                }
            }
            // 右下
            if (x + 1 < gx && y + 1 < gy) {
                if (mm[toKey(x + 1, y + 1)]) {
                    size++
                }
            }
            return size
        }

        function toKey(x, y) {
            return x + '-' + y
        }

        /*
          1蓝色
          2深绿色
          3红色
          4深蓝色
          5褐色
          6青色
          7深红色
          8黑色
           */
        const styleFill1 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#1E90FF'
            }),
            styleFill2 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#32CD32'
            }),
            styleFill3 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#B22222'
            }),
            styleFill4 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#0000CD'
            }),
            styleFill5 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#D2691E'
            }),
            styleFill6 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#7FFF00'
            }),
            styleFill7 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#8B0000'
            }),
            styleFill8 = new PIXI.TextStyle({
                fontWeight: 'bold',
                fill: '#000000'
            })

        // 渲染出雷的数量
        function renderMineSize(x, y, c) {
            let g = gridMap[x][y]
            c = g._mineRoundCount
            // 已经显示过了
            if (g._mineShow) {
                return false
            }
            g._mineShow = true
            if (!c) {
                // 是空白块，渲染周围的显示出来
                renderRoundGrid(x, y)
                return false
            }
            let basicText
            if (c === 1) {
                basicText = new PIXI.Text('' + c, styleFill1)
            } else if (c === 2) {
                basicText = new PIXI.Text('' + c, styleFill2)
            } else if (c === 3) {
                basicText = new PIXI.Text('' + c, styleFill3)
            } else if (c === 4) {
                basicText = new PIXI.Text('' + c, styleFill4)
            } else if (c === 5) {
                basicText = new PIXI.Text('' + c, styleFill5)
            } else if (c === 6) {
                basicText = new PIXI.Text('' + c, styleFill6)
            } else if (c === 7) {
                basicText = new PIXI.Text('' + c, styleFill7)
            } else if (c === 8) {
                basicText = new PIXI.Text('' + c, styleFill8)
            } else {
                basicText = new PIXI.Text('' + c)
            }
            basicText.x = y * 50 + 18
            basicText.y = x * 50 + 10
            app.stage.addChild(basicText)

            /*
            1蓝色
            2深绿色
            3红色
            4深蓝色
            5褐色
            6青色
            7深红色
            8黑色
            */
        }

        // 显示周围的格子
        function renderRoundGrid(x, y) {
            // 左上
            if (x - 1 >= 0 && y - 1 >= 0) {
                let g = gridMap[x - 1][y - 1]
                renderMineSize(x - 1, y - 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 上
            if (x - 1 >= 0) {
                let g = gridMap[x - 1][y]
                renderMineSize(x - 1, y, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 右上
            if (x - 1 >= 0 && y + 1 < gy) {
                let g = gridMap[x - 1][y + 1]
                renderMineSize(x - 1, y + 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 左
            if (y - 1 >= 0) {
                let g = gridMap[x][y - 1]
                renderMineSize(x, y - 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 右
            if (y + 1 < gy) {
                let g = gridMap[x][y + 1]
                renderMineSize(x, y + 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 左下
            if (x + 1 < gx && y - 1 >= 0) {
                let g = gridMap[x + 1][y - 1]
                renderMineSize(x + 1, y - 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 下
            if (x + 1 < gx) {
                let g = gridMap[x + 1][y]
                renderMineSize(x + 1, y, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
            // 右下
            if (x + 1 < gx && y + 1 < gy) {
                let g = gridMap[x + 1][y + 1]
                renderMineSize(x + 1, y + 1, g._mineRoundCount)
                g.texture = texture4
                g._mineShow = true
            }
        }

        // 左键
        function onClick() {
            if (isGameOver) {
                alert('game over')
                return false
            }

            if (this._mineShow) {
                return false
            }

            let key = toKey(this._mineX, this._mineY)
            console.log(key)
            if (!initMineFlag) {
                initMineFlag = true
                initMine(this._mineX, this._mineY)
                renderMineSize(this._mineX, this._mineY, this._mineRoundCount)
                this.texture = texture4
            } else {
                if (!this._mineMark) {
                    // this.texture = texture3
                    // if (Math.round(Math.random())) {
                    //   this.tint = 0xff0000
                    // } else {
                    //   this.tint = 0xffffff
                    // }
                    if (this._mineFlag) {
                        this.tint = 0xff0000
                        this.texture = texture3

                        isGameOver = true
                        alert('game over')
                        return false
                    } else {
                        renderMineSize(this._mineX, this._mineY, this._mineRoundCount)
                        this.texture = texture4
                    }
                }
            }

            // 检测是否完成
            isComplete()
        }

        // 右键
        function rightClick() {
            if (this._mineMark) {
                this._mineMark = false
                this.texture = texture
                this.tint = 0xffffff

                markMineSize--
            } else {
                this._mineMark = true
                this.texture = texture2
                this.tint = 0xffffff

                markMineSize++
            }

            let s = mineSize - markMineSize
            s = s < 0 ? 0 : s
            basicText.text = '还剩余 ' + s + ' 个雷'
        }

        // 是否完成
        function isComplete() {
            let c = 0
            // 判断剩余没有打开的格子是不是雷的数量
            for (let i = 0; i < gx; i++) {
                for (let j = 0; j < gy; j++) {
                    let g = gridMap[i][j]
                    if (!g._mineShow) {
                        c++
                    }
                }
            }
            if (c === mineSize) {
                isGameOver = true
                alert('is very good')
            }
        }
    }

    loadMine()

    const style = new PIXI.TextStyle({
        fontFamily: 'Arial',
        fontSize: 18,
        fontStyle: 'italic',
        fontWeight: 'bold',
        fill: ['#ffffff', '#00ff99'], // gradient
        stroke: '#4a1850',
        strokeThickness: 5,
        dropShadow: true,
        dropShadowColor: '#000000',
        dropShadowBlur: 4,
        dropShadowAngle: Math.PI / 6,
        dropShadowDistance: 6,
        wordWrap: true,
        wordWrapWidth: 440
    })
    // 添加文字
    const basicText = new PIXI.Text('还剩余 ' + mineSize + ' 个雷', style)
    basicText.x = 100
    basicText.y = 510
    app.stage.addChild(basicText)
}

/*
1.鼠标左键触发事件：

click：点击事件

mousedown：鼠标按下

mousemove：鼠标移动

mouseout：鼠标移出

mouseover：鼠标经过

mouseup：鼠标松开

mouseupoutside：鼠标按下，移出对象松开

2.鼠标右键触发事件：

rightclick：点击事件

rightdown：鼠标按下

rightup：鼠标松开

rightupoutside：鼠标按下，移出对象松开

3.触摸屏触发事件：

touchcancel：触摸系统cancels键

touchend：触摸结束

touchendoutside：触摸开始，移出对象松开

touchmove：触摸移动

touchstart：触摸开始

4.兼容鼠标和触摸屏的共同触发：

pointercancel：触发系统cancels键

pointerdown：触发按下

pointermove：触发移动

pointerout：触发移出

pointerover：触发经过

pointertap：触发点击

pointerup：触发松开

*/
